#include "chatserver.hpp"
#include "PCHAT.pb.h"
#include "chatservice.hpp"

#include <functional>

using namespace std;
using namespace std::placeholders;

ChatServer::ChatServer(EventLoop* loop,
	const InetAddress& listenAddr,
	const string& nameArg)
	: m_server(loop, listenAddr, nameArg), m_loop(loop)
{
	m_server.setConnectionCallback(std::bind(&ChatServer::onConnection, this, _1));
	m_server.setMessageCallback(std::bind(&ChatServer::onMessage, this, _1, _2, _3));
	m_server.setThreadNum(6);	//线程数量推荐设置为CPU核心数
}

void ChatServer::start()
{
	m_server.start();
}

void ChatServer::onConnection(const TcpConnectionPtr& conn) {
	if (!conn->connected()) {
		//客户端断开连接(客户端断开连接，代表之前肯定是登录的，那么在_userConnMap表中一定有记录)
		ChatService::getInstance().clientCloseException(conn);
		conn->shutdown();
	}
}

void ChatServer::onMessage(const TcpConnectionPtr& conn, Buffer* buffer, Timestamp time) {
	auto buf = buffer->retrieveAllAsString();

	ChatMessage chat_msg;
	chat_msg.ParseFromString(buf);

	//获取msg_type对应的业务处理器handle(就是一个处理这个消息的一个函数)
	auto msgHandler = ChatService::getInstance().getHandler(chat_msg.msg_type());
	//这里就把网络模块的代码和业务模块的代码分开了,业务模块怎么修改网络模块这块都不需要修改
	msgHandler(conn, chat_msg, time);
}